package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/addToCartServlet")
public class addToCartServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 从 session 获取 userId
		HttpSession session = request.getSession();
		String userIdStr = (String) session.getAttribute("userId");  // 假设存储的是 String 类型的 userId

		if (userIdStr == null) {
			ResponseUtils.sendResponse(response, "用户未登录", "login.jsp");
			return;
		}

		// 尝试将 userIdStr 转换为 Integer
		Integer userId = null;
		try {
			userId = Integer.parseInt(userIdStr);
		} catch (NumberFormatException e) {
			ResponseUtils.sendResponse(response, "无效的用户ID", "login.jsp");
			return;
		}

		// 获取前端传递的商品ID和数量
		String productIdStr = request.getParameter("productId");
		String star = request.getParameter("star");
		String quantityStr = request.getParameter("quantity");

		// 校验商品ID和数量
		if (productIdStr == null || quantityStr == null || !quantityStr.matches("\\d+") || Integer.parseInt(quantityStr) <= 0) {
			ResponseUtils.sendResponse(response, "无效的商品ID或数量", "userinfo.jsp");
			return;
		}

		// 将商品ID，数量，积分转换为整数
		int productIdInt = Integer.parseInt(productIdStr);
		int quantity = Integer.parseInt(quantityStr);

		// 校验积分 (star)
		int getStar = 0;
		if (star != null) {
			try {
				getStar = Integer.parseInt(star);
				if (getStar < 0) {
					ResponseUtils.sendResponse(response, "积分不能为负数", "userinfo.jsp");
					return;
				}
			} catch (NumberFormatException e) {
				ResponseUtils.sendResponse(response, "无效的积分值", "userinfo.jsp");
				return;
			}
		}

		// 获取用户的收货地址
		String getUserAddressSql = "SELECT address FROM users WHERE id = ?";
		String userAddress = null;

		DB db = new DB();
		try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getUserAddressSql)) {
			pstmt.setInt(1, userId);
			ResultSet rs = pstmt.executeQuery();

			// 检查用户是否存在并获取收货地址
			if (rs.next()) {
				userAddress = rs.getString("address");
			} else {
				ResponseUtils.sendResponse(response, "用户不存在", "login.jsp");
				return;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			ResponseUtils.sendResponse(response, "数据库错误，无法获取用户收货地址", "userinfo.jsp");
			return;
		}

		// 获取商品单价和商品信息
		String getProductSql = "SELECT price FROM products WHERE id = ?";
		double unitPrice = 0;
		try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(getProductSql)) {
			pstmt.setInt(1, productIdInt);
			ResultSet rs = pstmt.executeQuery();

			// 检查商品是否存在
			if (rs.next()) {
				unitPrice = rs.getDouble("price");
			} else {
				ResponseUtils.sendResponse(response, "商品不存在", "userinfo.jsp");
				return;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			ResponseUtils.sendResponse(response, "数据库错误，无法获取商品信息", "userinfo.jsp");
			return;
		}

		// 计算总价
		double totalPrice = unitPrice * quantity;

		// 插入购物车信息
		String insertCartSql = "INSERT INTO userCart (user_id, product_id, quantity, order_time, unit_price, total_price, user_address ,star) VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?, ?, ?)";
		try (Connection conn = db.createConn(); PreparedStatement insertPstmt = conn.prepareStatement(insertCartSql)) {
			insertPstmt.setInt(1, userId);
			insertPstmt.setInt(2, productIdInt);
			insertPstmt.setInt(3, quantity);
			insertPstmt.setDouble(4, unitPrice);
			insertPstmt.setDouble(5, totalPrice);
			insertPstmt.setString(6, userAddress);
			insertPstmt.setInt(7, getStar);

			int rows = insertPstmt.executeUpdate();

			if (rows > 0) {
				ResponseUtils.sendResponse(response, "商品已成功添加到购物车", "userinfo.jsp");
			} else {
				ResponseUtils.sendResponse(response, "添加到购物车失败", "userinfo.jsp");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			ResponseUtils.sendResponse(response, "数据库错误，无法添加商品到购物车", "userinfo.jsp");
		}
	}
}
